package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.bean.SInventory;
import com.example.demo.common.exception.DataValidException;
import com.example.demo.mapper.SInventoryMapper;
import com.example.demo.mapper.SProductMapper;
import com.example.demo.mapper.SWarehouseMapper;
import com.example.demo.web.controller.SIventoryController;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class SInventoryService {
	@Autowired
	private SInventoryMapper siMapper;
	@Autowired
	private SProductMapper spMapper;
	@Autowired
	private SWarehouseMapper swMapper;
	
	//查找所有库存信息
	public PageInfo<SInventory> findAllByPage(int pageNum,int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<SInventory> list= siMapper.selectAll();
		if (list==null) {
			list=new ArrayList<>(0);
		}
		return new PageInfo<SInventory>(list);
	}
	
	//通过条件查找库存信息
	public PageInfo<SInventory> findByCondition(Integer productId,
			Integer warehouseId,
			int pageNum,int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		List<SInventory> list=siMapper.selectByCondition(productId, warehouseId);
		if (list==null) {
			list=new ArrayList<>(0);
		}
		return new PageInfo<>(list);
	}
	
	//保存或更新库存信息
	public void saveOrUpdate(SInventory si) {
		//判断输入的信息是否完整
		if (si.getProductId()==null||si.getWarehouseId()==null) {
			throw new DataValidException("请填写完整信息");
		}else {
			//在数据库中查找外键是否存在
			if (spMapper.selectByPrimaryKey(si.getProductId())==null||swMapper.selectByPrimaryKey(si.getWarehouseId())==null) {
				throw new DataValidException("外键信息不存在");
			}
		}
		if (siMapper.selectByPrimaryKey(si.getProductId(), si.getWarehouseId())!=null) {
			siMapper.updateByPrimaryKey(si);
		}else {
			siMapper.insert(si);
		}
	}
	//删除库存信息
	public int delete(Integer warehouseId,Integer productId) {
		//判断输入信息是否为空或不全
		if (warehouseId==null||productId==null) {
			throw new DataValidException("请输入完整的id");
		}
		//查找信息找不到提示报错
		if (siMapper.selectByPrimaryKey(productId, warehouseId)==null) {
			throw new DataValidException("删除失败");
		}
		siMapper.deleteByPrimaryKey(productId, warehouseId);
		return 0;
	}
	
	//批量删除
	public int batchDelete(int [] warehouseId,int [] productId) {
		//判断是否为空
		if(warehouseId.length==0||productId.length==0) {
			throw new DataValidException("请选择一批完整的id");
		}
//		for (int i : warehouseId) {
//			for (int j : productId) {
//				if (siMapper.selectByPrimaryKey(j, i)==null) {
//					throw new DataValidException("删除失败");
//				}
//			}
//		}
		for (int i = 0; i < productId.length; i++) {
			if (siMapper.selectByPrimaryKey(productId[i], warehouseId[i])==null) {
				throw new DataValidException("删除失败");
			}
			siMapper.deleteByPrimaryKey(productId[i], warehouseId[i]);
		}
		//批量删除
		//siMapper.batchDelete(warehouseId, productId);
		return 0;
	}
}
